package models

import (
	. "gini2p/config"
	"gini2p/logger"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var configEngine *xorm.Engine

var parkEngine *xorm.Engine

var localEngine *xorm.Engine

var ebillsEngine *xorm.Engine

var i2pEngine *xorm.Engine

var mallpointsEngine *xorm.Engine

func InitSql() error {
	err := initSql(DBConf.ConfigCloudAddr, &configEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = initSql(DBConf.ParkCloudAddr, &parkEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = initSql(DBConf.LocalConfigAddr, &localEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = initSql(DBConf.EbillsAddr, &ebillsEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = initSql(DBConf.I2pAddr, &i2pEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = initSql(DBConf.MallPointsAddr, &mallpointsEngine)
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	err = InitRedis()
	if err != nil {
		logger.Error("sql", err)
		return err
	}

	return nil
}

func initSql(url string, e **xorm.Engine) error {
	var err error
	*e, err = xorm.NewEngine("mysql", url)
	if err != nil {
		logger.Error("sql", err.Error())
		return err
	}
	(*e).ShowSQL(true)
	(*e).SetMaxOpenConns(40)
	return nil
}
